package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annontation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        if(!(handler instanceof HandlerMethod)){
            return true ;
        }
        //此处以下二行代码写在判断外边,有利于每次操作都重置cookie时间
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        HandlerMethod method = (HandlerMethod) handler ;
        if(method.hasMethodAnnotation(RequireLogin.class)){
            if(user==null){
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false ;
            }
        }
        return true;
    }
}
